<?php


declare (strict_types=1);

namespace app\admin\model\admin;

use app\admin\model\store\MenuApi as MenuApiModel;
use app\common\model\admin\Menu as MenuModel;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 管理后台菜单模型
 * Class Menu
 * @package app\admin\model\admin
 */
class Menu extends MenuModel
{
    /**
     * 新增记录
     * @param $data
     * @return false|int
     */
    public function add(array $data)
    {
        return $this->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit(array $data)
    {
        // 判断上级角色是否为当前子级
        if (isset($data['parent_id']) && $data['parent_id'] > 0) {
            // 获取所有上级id集
            $parentIds = $this->getTopMenuIds($data['parent_id']);
            if (in_array($this['menu_id'], $parentIds)) {
                $this->error = '上级菜单不允许设置为当前子菜单';
                return false;
            }
        }
        // 如果模块是操作, 不允许修改上级菜单id
        if ($this['module'] == 20 && isset($data['parent_id'])) {
            unset($data['parent_id']);
        }
        return $this->save($data) !== false;
    }

    /**
     * 获取所有上级id集
     * @param int $menuId
     * @param null $menuList
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getTopMenuIds(int $menuId, $menuList = null)
    {
        static $ids = [];
        is_null($menuList) && $menuList = $this->getAll();
        foreach ($menuList as $item) {
            if ($item['menu_id'] == $menuId && $item['parent_id'] > 0) {
                $ids[] = $item['parent_id'];
                $this->getTopMenuIds($item['parent_id'], $menuList);
            }
        }
        return $ids;
    }

    /**
     * 设置菜单的API权限
     * @param array $data
     * @return bool|int
     */
    public function setApis(array $data)
    {
        if (!isset($data['apiIds']) || empty($data['apiIds'])) {
            $this->error = 'API权限不能为空';
            return false;
        }
        // 根据菜单id批量更新API关联记录
        return (new MenuApiModel)->updateByMenuId($this['menu_id'], $data['apiIds']);
    }

    /**
     * 删除菜单
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function remove()
    {
        $this->abc($this['menu_id']);
        return true;
        // 判断是否存在下级菜单
//        if (self::detail(['parent_id' => $this['menu_id']])) {
//            $this->error = '当前菜单下存在子菜单或操作，请先删除';
//            return false;
//        }
//        return $this->delete();
    }

    public function abc($menu_id)
    {
        MenuApiModel::deleteAll(['menu_id' => $menu_id]);
        $this->where(['menu_id' => $menu_id])->delete();
        $list = $this->where(['parent_id' => $menu_id])->select();
        foreach ($list as $v) {
            $this->abc($v->menu_id);
            // 清空菜单与API关联关系
            MenuApiModel::deleteAll(['menu_id' => $v->menu_id]);
            $this->where(['menu_id' => $v->menu_id])->delete();
        }
    }

    /**
     * 根据菜单ID集获取列表
     * @param array $menuIds
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getListByIds(array $menuIds)
    {
        // 菜单列表
        $list = static::getAll([['menu_id', 'in', $menuIds]]);
        // 整理菜单绑定的apiID集
        return (new static)->getTreeData($list);
    }

}
